/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin.booking;

import app.Const;
import app.models.DaoKit;
import app.models.booking.DiningCategory;
import app.models.booking.DiningNums;
import app.models.brand.Brand;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;

import java.util.List;

import static app.controllers.admin.booking.DiningController.ADMIN_BOOKING_DINING;
import static app.controllers.admin.booking.DiningController.BRAND;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-27 0:32
 * @since JDK 1.6
 */
public class CategoryController extends BasicController {

    /**
     * The index route.
     */
    public void index() {

        long brand = getParaToLong(0, 0l);
        if (brand == 0) {
            redirect(ADMIN_BOOKING_DINING);
            return;
        }
        setAttr(BRAND, Brand.dao.findById(brand));
        render("index.ftl");
    }

    public void list() {

        long brand = getParaToLong(0, 0l);
        if (brand == 0) {
            renderJson(AjaxMessage.nodata());
        }
        List<DiningCategory> categories = DiningCategory.dao.findByBrand(brand);
        renderJson(AjaxMessage.ok(categories));
    }

    public void item() {
        int id = getParaToInt(0, 0);
        DiningCategory category;
        if (id > 0) {
            category = DiningCategory.dao.findById(id);
            setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        } else {
            category = new DiningCategory();
            category.set(BRAND, getPara(BRAND));
            setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        }
        setAttr("diningCategory", category);
        render("item.ftl");
    }

    public void remove(){
        int id = getParaToInt(0, 0);
        if(id > 0){
            DiningCategory.dao.deleteById(id);
            DiningNums.dao.deleteByCategory(id);
        }
        renderJson(AjaxMessage.ok());
    }

    public void save() {
        DiningCategory category = getModel(DiningCategory.class);
        if (DaoKit.isNew(category)) {
            category.save();
        } else {
            category.update();
        }
        renderJson(AjaxMessage.ok(category));
    }
}